package com.dfdchem.imd.kaiwu.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.adapter.ContactAdapter;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.interfaces.RecyclerItemClickListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.model.RespList;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;


/**
 * 新闻公告
 */
@Route(path = RouterPath.CONTACT_ACTIVITY)
public class ContactActivity extends BaseActivity implements View.OnClickListener, OnRefreshListener, OnHttpResponseListener, OnLoadMoreListener {

    private static final String TAG = "ContactActivity";

    private RecyclerView recyclerView;
    private ContactAdapter contactAdapter;
    private LinearLayoutManager layoutManager;

    private RefreshLayout refreshLayout;

    public static final int request_code_get_user_list = 1;

    private int request_page = 1;
    private int request_limit = 999;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        recyclerView = findView(R.id.recycler_view);

        refreshLayout = findViewById(R.id.refreshLayout);

        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // specify an adapter (see also next example)
        contactAdapter = new ContactAdapter(this);
        recyclerView.setAdapter(contactAdapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        dividerItemDecoration.setDrawable(getDrawable(R.drawable.profile_list_divider));
        recyclerView.addItemDecoration(dividerItemDecoration);

    }

    @Override
    public void initData() {
        loadData();
    }

    private void loadData(){
        runThread(TAG + "getUserList", new Runnable() {
            @Override
            public void run() {
                if (request_page <= 0) {
                    request_page = 1;
                }
                RequestUtil.get_user_list(request_page, request_limit, request_code_get_user_list, ContactActivity.this);
            }
        });

        // 设置默认的超时，防止卡住
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (refreshLayout.getState() == RefreshState.Refreshing) {
                    refreshLayout.finishRefresh(250);
                } else if (refreshLayout.getState() == RefreshState.Loading) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        },10000); // 延时10秒
    }

    @Override
    public void initEvent() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(context, recyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {

                        User fromUser = contactAdapter.getUsers().get(position);
                        User toUser = DataManager.getInstance().getUser();
                        if (toUser == null || toUser.getId() <= 0) {
                            return;
                        }
                        ARouter.getInstance()
                                .build(RouterPath.MESSAGE_DETAIL_ACTIVITY)
                                .withInt("MESSAGE_TYPE", MessageDetailActivity.MESSAGE_TYPE_USER)
                                .withObject("fromUser", fromUser)
                                .withObject("toUser", toUser)
                                .navigation(ContactActivity.this);
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        Log.d(TAG, "addOnItemTouchListener onLongItemClick");
                    }
                })
        );
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onReturnClick(View v) {
        enterAnim = R.anim.left_push_in;
        exitAnim = R.anim.right_push_out;
        this.finish();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        Log.d(TAG, "onRefresh");
        request_page = 1;
        refreshLayout.setEnableLoadMore(true);
        loadData();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        Log.d(TAG, "onLoadMore");
        request_page ++;
        loadData();
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        Log.d(TAG, "onHttpResponse requestCode:" + requestCode + " resultJson:" + resultJson);
        if (requestCode == request_code_get_user_list) {
            dismissProgressDialog();
        }
        if (e != null) {
            Toast.makeText(getActivity(), "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_get_user_list:
                RespList<User> resp = JSON.parseRespList(resultJson, User.class);
                if (resp == null || resp.getCode() != 200 ) {
                    Toast.makeText(this, resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    if (refreshLayout.getState() == RefreshState.Refreshing) {
                        refreshLayout.finishRefresh(250);
                    } else if (refreshLayout.getState() == RefreshState.Loading) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                    return;
                }
                List<User> users = resp.getData();
                if (users == null) {
                    if (refreshLayout.getState() == RefreshState.Refreshing) {
                        refreshLayout.finishRefresh(250);
                    } else if (refreshLayout.getState() == RefreshState.Loading) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                    Toast.makeText(this, "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }

                request_page = resp.getPage();
                request_limit = resp.getLimit();

                if (refreshLayout.getState() == RefreshState.None || refreshLayout.getState() == RefreshState.Refreshing) {
                    if (users.size() > 0) {
                        contactAdapter.setUsers(users);
                    }
                    refreshLayout.finishRefresh(250);
                } else if (refreshLayout.getState() == RefreshState.Loading) {
                    if (users.size() > 0) {
                        List<User> tmpUsers = contactAdapter.getUsers();
                        if (tmpUsers != null) {
                            tmpUsers.addAll(users);
                        } else {
                            tmpUsers = users;
                        }
                        contactAdapter.setUsers(tmpUsers);
                    }
                    if (users.size() == 0 && request_page * request_limit >= resp.getRecordsTotal()) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishLoadMore(250);
                    }
                }

                if (users.size() > 0) {
                    contactAdapter.notifyDataSetChanged();
                }
                break;

        }
    }
}
